package com.qiqijuice.sales;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;

import com.db4o.ObjectContainer;

public class AppFrame {
	public static int EVT_PRODUCT = 0x1000;
	public static int EVT_CASHIER = 0x1001;
	public static int EVT_SALES   = 0x1002;
	
	static AppFrame appFrame = null;
	
	Display display;
	Shell frame;
	StackLayout layout;
	MainAppMenu mainMenu;
	ProductView productView;
	OrderView 	orderView;
	SalesView	salesView;
	
	public static AppFrame getInst() {
		return appFrame;
	}
	
	public AppFrame(Display display) throws Exception {
		if (appFrame != null)
			throw new Exception("AppFrame:AppFrame - can not initialize frame twice");
		
		appFrame = this;
		
		this.display = display;
		frame = new Shell(display, SWT.TITLE | SWT.RESIZE | SWT.CLOSE);
		frame.setMaximized(true);
		layout = new StackLayout();
		
		frame.setLayout(layout);
		
		mainMenu = new MainAppMenu(frame);
		
		ObjectContainer oc = Db4oContainerFactory.getDB();
		productView = new ProductView(frame);
		productView.refreshCategoryData();
		
		orderView = new OrderView(frame);
		
		salesView = new SalesView(frame);
		
		mainMenu.addListener(EVT_PRODUCT, new Listener(){

			@Override
			public void handleEvent(Event event) {
				layout.topControl = productView;
				frame.layout();
			}
			
		});
		
		mainMenu.addListener(EVT_CASHIER, new Listener(){

			@Override
			public void handleEvent(Event event) {
				layout.topControl = orderView;
				frame.layout();
			}
			
		});
		
		mainMenu.addListener(EVT_SALES, new Listener(){

			@Override
			public void handleEvent(Event event) {
				layout.topControl = salesView;
				frame.layout();
			}
			
		});
		
		layout.topControl = mainMenu;
		
		frame.layout();
	}
	
	public Display getDisplay() {
		return display;
	}
	
	
	public ProductView getProductView() {
		return productView;
	}

	public void setProductView(ProductView productView) {
		this.productView = productView;
	}
	
	static public void main(String[] argv) {
		Display display = new Display();
		AppFrame view;
		
		try {
			view = new AppFrame(display);
			view.frame.open();

			while (!view.frame.isDisposed()) {
				if (!display.readAndDispatch())
					display.sleep();
			}
			
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			display.dispose();
		}
	}
}

